package com.hmyd.hmyd_android.ui;

import java.math.BigDecimal;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Investment;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.TriangleRateView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 个人票据详情
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_tickets_details)
public class TicketsDetailsActivity extends BasicActivity implements OnClickListener {
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.investment_description)
	private View mInvestmentDescription;
	@ViewInject(R.id.investment_history)
	private View mInvestmentHistory;
	@ViewInject(R.id.now_investment)
	private Button mNowInvestment;

	@ViewInject(R.id.type)
	private TextView type;
	@ViewInject(R.id.title)
	private TextView title;
	@ViewInject(R.id.interest_rate)
	private TextView investment_rate;
	@ViewInject(R.id.interest_rate_sp)
	private TextView investment_rate_sp;
	@ViewInject(R.id.tickets_tips_tv)
	private TextView tickets_tips_tv;
	@ViewInject(R.id.tickets_tips)
	private LinearLayout tipsContent;
	@ViewInject(R.id.dailyMInterest)
	private TextView dailyMInterest;
	@ViewInject(R.id.bill_mount)
	private TextView bill_mount;

	@ViewInject(R.id.money)
	private TextView money;
	@ViewInject(R.id.sui)
	private TextView sui;
	@ViewInject(R.id.day)
	private TextView day;

	// @ViewInject(R.id.introduce)
	// private View introduce;
	@ViewInject(R.id.tag)
	private TextView tag;
	@ViewInject(R.id.assetsdetail_guide)
	private ImageView assetsdetail_guide;

	@ViewInject(R.id.triangle)
	private TriangleRateView triangle;

	private static String SER_KEY = "SER_KEY";
	private Investment investment;

	@ViewInject(R.id.countdown_layout)
	private View mCountdownLayout;
	@ViewInject(R.id.h)
	private TextView mH;
	@ViewInject(R.id.m)
	private TextView mM;
	@ViewInject(R.id.s)
	private TextView mS;
	long l;
	long hour;
	long min;
	long s;
	private boolean isCountdown = false;
	private final int GET = 1;
	private final int BILL_SUM = 4;
	private double rt;

	Handler handler = new Handler();
	Runnable runnable = new Runnable() {
		int p = 0;

		@Override
		public void run() {

			isCountdown = true;

			mH.setText(hour + "");
			mM.setText(min + "");
			mS.setText(s + "");

			if (l >= 1000) {
				l = l - 1000;

				hour = (l / (60 * 60 * 1000));
				min = ((l / (60 * 1000)) - hour * 60);
				s = (l / 1000 - hour * 60 * 60 - min * 60);

				if (p == 100) {
					p = 0;
				} else {
					p++;
				}
			} else {
				p = 0;

				mNowInvestment.setVisibility(View.VISIBLE);
				mNowInvestment.setOnClickListener(TicketsDetailsActivity.this);
				mNowInvestment.setText("立即投资");

				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.endTime - AppBasic.ServerTime;
			}

			handler.postDelayed(this, 1000);
		}
	};

	final Handler handlerStop = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				isCountdown = false;
				handler.removeCallbacks(runnable);
				break;
			}
			super.handleMessage(msg);
		}
	};

	public static Intent getIntent(Context context, Investment investment) {
		Intent intent = new Intent(context, TicketsDetailsActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putSerializable(SER_KEY, investment);
		intent.putExtras(mBundle);

		return intent;
	}

	public static Intent getIntent(Context context, String investmentId) {
		Intent intent = new Intent(context, TicketsDetailsActivity.class);
		intent.putExtra("investmentId", investmentId);

		return intent;
	}

	@Override
	protected void onResume() {
		super.onResume();

		String investmentId = getIntent().getStringExtra("investmentId");

		// 获取项目详情
		if (investment != null) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", investment.id);
			params.addBodyParameter("itemRateId", investment.itemRateId);

			onRequest(GET, UrlConstant.BILL_DETAIL, HttpMethod.GET, params);
		} else if (!TextUtils.isEmpty(investmentId)) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", investmentId);
			params.addBodyParameter("itemRateId", investment.itemRateId);

			onRequest(GET, UrlConstant.BILL_DETAIL, HttpMethod.GET, params);
		}
		// 获取资金规模
		RequestParams params = new RequestParams();
		params.addBodyParameter("itemRateId", investment.itemRateId);
		onRequest(BILL_SUM, UrlConstant.BILL_SUM, HttpMethod.POST, params);
	}

	@Override
	public void onPostSuccess(int postId, String result) {

		Gson gson = new Gson();
		switch (postId) {
		case GET:
			java.lang.reflect.Type type2 = new TypeToken<Investment>() {
			}.getType();
			investment = gson.fromJson(result, type2);

			setData(investment);
			break;
		case BILL_SUM:
			try {
				JSONObject jsonObject = new JSONObject(result);
				bill_mount.setText(jsonObject.getString("investSum"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onPostFailure(int postId, String msg) {

	}

	@Override
	protected void setParams() {
		home_title.setOnTouchListener(touch);
		investment = (Investment) getIntent().getSerializableExtra(SER_KEY);
		home_title_txt.setText(investment.title);

		String[] name = { "银行存款", "国泰惠民益贷" };
		String rateStr = investment.rate;
		
		if(rateStr.contains("+")){
			double rt = getRateLast(rateStr);
			//double rate = 15.0;
			double[] rate1 = { getRate(AppBasic.app.BackRates), Double.valueOf(rt) };
			triangle.setPositionLabel(1, rateStr+"%");
			triangle.setRate(rate1);
		}else{
			double[] rate1 = { getRate(AppBasic.app.BackRates), Double.valueOf(investment.rate) };
			triangle.setRate(rate1);

		}
		
		int[] colors = { R.color.login_btn_bg, R.color.text_orange };
		triangle.setName(name);
		triangle.setColors(colors);
		
	}

	private void setData(Investment investment) {

		if (investment != null) {
			// title.setText(investment.title);

			/**
			 * 年化利率图计算
			 */
			rt = 0;
			getRateView(investment);

			// 设置textview字体大小
			Utils.changeTextSize(investment.investInfo, money, getResources().getColor(R.color.white));
			Utils.changeTextSize(investment.smartWay, sui, getResources().getColor(R.color.white));
			Utils.changeTextSize(investment.repayMethod, day, getResources().getColor(R.color.white));


			rt = getRateLast(investment.rate);
			dailyMInterest.setText(investment.dailyMInterest);

			tipsContent.removeAllViews();
			for (int i = 0; i < investment.tips.size(); i++) {
				TextView textView = new TextView(TicketsDetailsActivity.this);
				textView.setText(investment.tips.get(i).tip);
				Drawable drawable = getResources().getDrawable(R.drawable.piao_icon_safe);
				// / 这一步必须要做,否则不会显示.
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				textView.setCompoundDrawables(drawable, null, null, null);
				textView.setCompoundDrawablePadding(3);
				textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);

				tipsContent.addView(textView);
			}
			// 设置活动标签
			if (!TextUtils.isEmpty(investment.itemtagIcon)
					&& !TextUtils.isEmpty(investment.itemTagName)
					&& !TextUtils.isEmpty(investment.itemTagUrl)) {
				tag.setText(investment.itemTagName);
			}

			mNowInvestment.setBackgroundResource(R.color.text_orange);
			mNowInvestment.setEnabled(true);

			if ("invest".equals(investment.itemStatus)) {
				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.endTime - AppBasic.ServerTime;

				if (!isCountdown) {
					handler.postDelayed(runnable, 0);
				}
			}

			if ("full".equals(investment.itemStatus) || "repay".equals(investment.itemStatus)
					|| "success".equals(investment.itemStatus)) {
				mNowInvestment.setEnabled(false);
				mNowInvestment.setText("已被抢光");
				mNowInvestment.setBackgroundResource(R.color.text_gray);

				mCountdownLayout.setVisibility(View.INVISIBLE);
			}

			if ("reserve".equals(investment.itemStatus)) {
				mNowInvestment.setEnabled(false);
				mNowInvestment.setText("敬请期待");
				mNowInvestment.setOnClickListener(null);
				mNowInvestment.setBackgroundResource(R.color.text_gray);

				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.startTime - AppBasic.ServerTime;

				if (!isCountdown) {
					handler.postDelayed(runnable, 0);
				}
			}

			if ("order".equals(investment.itemStatus)) {
				mNowInvestment.setText("立即预约");
				mNowInvestment.setBackgroundResource(R.color.text_orange);
				mNowInvestment.setOnClickListener(this);

				mCountdownLayout.setVisibility(View.VISIBLE);

				l = investment.startTime - AppBasic.ServerTime;

				if (!isCountdown) {
					handler.postDelayed(runnable, 0);
				}
			}

		}

	}
	
	/**
	 * 获取利率
	 * @param investment
	 * @param holder
	 */
	private void getRateView(Investment investment){
		String rate_value = investment.rate;
		String rate = "";
		String rate_sp = "";

		// 如果包含%， 删除所有%  手动添加
		rate_value = rate_value.contains("%") ? rate_value.replace("%", "") : rate_value;

		if (rate_value.contains("+")) {
			rate = rate_value.split("[+]")[0];
			rate_sp = rate_value.split("[+]")[1];

			investment_rate.setText(rate);
			investment_rate_sp.setText("% + "+rate_sp+"%");
		} else {
			investment_rate_sp.setVisibility(View.GONE);
			
			investment_rate.setText(rate_value + "%");
		}
	}

	/**
	 * 将字符串转换成Double类型
	 * 
	 * @param rate
	 * @return
	 */
	public double getRate(String rate) {
		double rt = 0;
		if (rate.contains("%")) {
			rt = Double.parseDouble(rate.replace("%", ""));
		}
		return rt;
	}

	private double getRateLast(String rate) {
		try {
			rate = rate.contains("%") ? rate.replace("%", "") : rate;
			
			if(rate.contains("+")) {
				String[] r = rate.split("[+]");
				return sum(Double.parseDouble(r[0].trim()), Double.parseDouble(r[1].trim()));
			} else {
				return Double.parseDouble(rate);
			}
		} catch (Exception e) {
			Utils.printException(e);
		}
		return 0;
	}

	/**
	 * double 相加
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public double sum(double d1, double d2) {
		BigDecimal bd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bd2 = new BigDecimal(Double.toString(d2));
		return bd1.add(bd2).doubleValue();
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	@OnClick({ R.id.now_investment, R.id.investment_history, R.id.investment_description })
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.now_investment:
			if (AppBasic.isLogin) {
				if (investment.period >= 30) {// 可用现金券 小惠钱包确认投资页面
					startActivity(TicketsWithCouponConfirmActivity.getIntent(TicketsDetailsActivity.this,
							investment.id, investment.type, investment.title, investment.rate,
							String.valueOf(investment.period), investment.periodUnit, 0,
							investment.endTime, investment.itemStatus, investment.baseAmount,
							investment.minInvestAmount, investment.totalAmount,
							investment.purchasedAmount, investment.itemRateId,
							investment.dailyMInterest));
				} else {// 不可用现金券 小惠钱包确认投资页面
					startActivity(TicketsConfirmActivity.getIntent(TicketsDetailsActivity.this,
							investment.id, investment.type, investment.title, investment.rate,
							String.valueOf(investment.period), investment.periodUnit, 0,
							investment.endTime, investment.itemStatus, investment.baseAmount,
							investment.minInvestAmount, investment.totalAmount,
							investment.purchasedAmount, investment.itemRateId,
							investment.dailyMInterest));
				}

			} else {
				startActivity(new Intent(TicketsDetailsActivity.this, LoginActivity.class));
			}
			break;
		case R.id.investment_history:
			startActivity(InvestmentHistoryActivity.getIntent(this, investment.id, true,investment.itemRateId));
			break;
		case R.id.investment_description:
			startActivity(InvestmentDescriptionActivity.getIntent(this, investment.id));
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (handlerStop != null && handler != null && runnable != null) {
			Message message = new Message();
			message.what = 1;
			handlerStop.sendMessage(message);
		}
	}

}
